package com.jy.app.lib.net;

import android.content.Intent;

import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.jy.app.lib.R;
import com.jy.app.lib.application.BaseApplication;
import com.jy.app.lib.base.Constants;
import com.jy.app.lib.bean.BaseResponse;
import com.jy.app.lib.utils.JsonUtil;
import com.jy.app.lib.utils.LogUtil;
import com.jy.app.lib.utils.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import cz.msebera.android.httpclient.Header;


/**
 * Created by jan on 2016/3/28.
 */
public class HttpResponseHandler<T> extends AsyncHttpResponseHandler implements BaseResponseHandler<T> {

    private TypeReference<T> type = null;

    public HttpResponseHandler(TypeReference<T> type) {
        this.type = type;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onSuccess(T response) {
    }

    @Override
    public void onSuccess(T response, String msg) {
        onSuccess(response);
    }

    @Override
    public void onFailure(int failCode, String failSource) {
    }


    @Override
    public void onSuccess(int i, Header[] headers, byte[] bytes) {
        try {
            String successContent = new String(bytes, "UTF-8");
            if(HttpUtil.ENABLE_LOG){
                LogUtil.d("[HttpUtils]->response:"+successContent);
            }
            BaseResponse<T> res = JsonUtil.parseObject(successContent, new TypeReference<BaseResponse<T>>() {
                    });
            if (res.getCode() == 0||res.getCode() == 200) {
                if (res.getData() != null && !"".equals(res.getData().toString().trim())) {
                    Type type_ = ((ParameterizedType) type.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
                    if (type_.equals(String.class)) {
                        onSuccess((T) res.getData(),res.getMsg());
                    } else if (type_.equals(Boolean.class)) {
                        onSuccess((T) Boolean.valueOf((Boolean) res.getData()),res.getMsg());
                    } else if (type_.equals(Integer.class)) {
                        onSuccess((T) Integer.valueOf((Integer) res.getData()),res.getMsg());
                    } else if (type_.equals(Double.class)) {
                        onSuccess((T) Double.valueOf((Double) res.getData()),res.getMsg());
                    } else {
                        onSuccess((T) JsonUtil.parseObject(res.getData().toString(), this.type),res.getMsg());
                    }
                } else {
                    onSuccess(null,res.getMsg());
                }
            } else {
                try {
                    if (res.getCode() == 500) {
                        ToastUtils.toastShort(BaseApplication.appContext, "账号登录已失效，请重新登录");
                        BaseApplication.appContext.startActivity(new Intent(BaseApplication.appContext, Class.forName(BaseApplication.loginActivity))
                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                        | Intent.FLAG_ACTIVITY_CLEAR_TASK).putExtra(Constants.KEY_NEED_CLEANPWD, true));
                    }else {
                        onFailure(res.getCode(), res.getMsg());
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LogUtil.e("onSuccess",e);
            onFailure(10000, "数据处理异常");
        } catch (Exception e) {
            e.printStackTrace();
            onFailure(10000, "数据处理异常");
        }
    }

    @Override
    public void onFailure(int i,Header[] headers, byte[] bytes, Throwable throwable) {
        if(bytes!=null){
            try {
                String content = new String(bytes,"UTF-8");
                onFailure(i,content);
            } catch (UnsupportedEncodingException e) {
                onFailure(10000,"onSuccess has error:"+e.getLocalizedMessage());
                e.printStackTrace();
            }
        }else{
            onFailure(i,BaseApplication.appContext.getString(R.string.your_network_not_ok));
        }
    }
}
